class Solution {
    private int[] elem ;
    private int usedSize;
    public int[] smallestK(int[] arr, int k) {
        elem = new int[arr.length] ;
        usedSize = arr.length ;
        if(arr.length == 0) return elem;
        for(int i = 0 ; i<arr.length ; i++){
            elem[i] = arr[i];
        }
        for(int parent = ((arr.length-1-1)/2) ; parent >= 0 ; parent--){
            shiftDown(parent ,usedSize);
        }
        int[] arr2 = new int[k];
        for(int i = 0 ; i< k ; i++){
            arr2[i] = poll();
        }
        return arr2 ;
    }

    private void shiftDown(int parent  , int usedSize){
        int child = parent*2 + 1 ;
        while(child < usedSize){
            if(child+1 < usedSize && elem[child] > elem[child+1]){
                child ++ ;
            }
            if(elem[child] < elem[parent]){
                swap(child , parent);
                parent  = child ;
                child = parent*2+1 ;
            }else{
                break ;
            }
        }

    }
    private int poll(){
        int tmp = elem[0] ;
        elem[0] = elem[usedSize-1];
        usedSize -- ;
        shiftDown(0 ,usedSize);
        return tmp ;
    }

    private void swap(int parent , int child){
        int tmp = elem[parent];
        elem[parent] = elem[child];
        elem[child] = tmp ;
    }

}